package com.koron.css2.contractmanage.impl;

import cn.hutool.core.util.ObjectUtil;
import com.koron.css2.ServerInterface;
import com.koron.css2.contractmanage.Enum.ContractStatusEnum;
import com.koron.css2.contractmanage.Enum.ContractTypeEnum;
import com.koron.css2.contractmanage.bean.ContractManageBean;
import com.koron.css2.contractmanage.exception.ContractException;
import com.koron.css2.contractmanage.mapper.ContractManageMapper;
import com.koron.css2.contractmanage.service.EcContratServiceImpl;
import com.koron.css2.contractmanage.util.EcConstant;
import com.koron.css2.contractmanage.vo.UserInfoVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import net.qiyuesuo.v3sdk.utils.SdkResponse;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.Arrays;

/**
 * 合同作废
 *
 * @date 2023/4/17 10:03
 */
public class ContractManageDelete implements ServerInterface {
    private EcContratServiceImpl ecContratService = new EcContratServiceImpl();

    /**
     * 签约进行中、签约完成、已上传合同附件状态才能作废合同
     */
    private static final String ALLOW_CANCEL_CONTRACT_STATUS =  ContractStatusEnum.CONTRACT_STATUS_1.getContractStatus() + ","
            + ContractStatusEnum.CONTRACT_STATUS_2.getContractStatus() + ","
            + ContractStatusEnum.CONTRACT_STATUS_7.getContractStatus();

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            ContractManageMapper mapper = factory.getMapper(ContractManageMapper.class);
            ContractManageBean bean = JsonUtils.objectToPojo(req.getData(), ContractManageBean.class);
            if (bean == null) {
                throw new ContractException("合同作废请求参数不能为空！");
            }
            //校验合同字段
            checkContractManageBean(bean, userInfo);

            // 用户号
            String userNo = bean.getUserNo();
            // 合同类型
            String contractType = bean.getContractType();
            // 合同状态
            String contractStatus = bean.getContractStatus();

            /**
             * 如果是电子合同，并且状态是签署中的，调签章平台的撤回合同接口。
             * 如果是电子合同，并且状态是已签署的，调签章平台的作废合同接口。
             */
            if (ContractTypeEnum.CONTRACT_TYPE_2.getContractType().equals(contractType) || ContractTypeEnum.CONTRACT_TYPE_0.getContractType().equals(contractType)) {
                UserInfoVO userInfoVO = mapper.getUserInfoByUserNo(bean.getUserNo());
                if (ObjectUtil.isNull(userInfoVO)){
                    userInfoVO = mapper.getTempUserInfoByUserNo(bean.getUserNo());
                }
                if (userInfoVO == null || StringUtils.isEmpty(userInfoVO.getUserNo())) {
                    throw new ContractException("根据户号[" + bean.getUserNo() + "]找到的用户信息为空！");
                }
                // 假如合同属于签署中 直接撤回
                if (ContractStatusEnum.CONTRACT_STATUS_1.getContractStatus().equals(contractStatus)){
                    SdkResponse responseObj = ecContratService.ecContractRecalled(Long.valueOf(bean.getRecordId()),userInfoVO);
                    logger.debug(bean.getUserNo() + "合同撤回,responseObj:" + JsonUtils.objectToJson(responseObj));
                    if (EcConstant.MESSAGE_SUCCESS != responseObj.getCode()) {
                        throw new ContractException("电子合同撤回失败！" + responseObj.getCode() + ":" + responseObj.getMessage());
                    }
                }
                // 假如合同属于已签署 直接作废
                if (ContractStatusEnum.CONTRACT_STATUS_2.getContractStatus().equals(contractStatus)){
                    SdkResponse responseObj = ecContratService.ecContractCancel(Long.valueOf(bean.getRecordId()));
                    logger.debug(bean.getUserNo() + "合同作废,responseObj:" + JsonUtils.objectToJson(responseObj));
                    if (EcConstant.MESSAGE_SUCCESS != responseObj.getCode()) {
                        throw new ContractException("电子合同作废失败！" + responseObj.getCode() + ":" + responseObj.getMessage());
                    }
                }
            }

            if (Arrays.asList(WATER_CONTRACT).contains(bean.getContractType())){
                // 更新用户合同状态信息
                int clearUserContr = mapper.deleteContractByUserNo(userNo);
                if (clearUserContr<1){
                    clearUserContr=mapper.deleteTempContractByUserNo(userNo);
                }
                if (clearUserContr < 1) {
                    throw new ContractException("更新用户合同状态失败！");
                }
            }

            //更新合同表状态
            int cancelContract = deleteContract(bean, userInfo, mapper);
            if (cancelContract < 1) {
                throw new ContractException("更新合同作废状态失败！");
            }
            return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "合同作废成功", void.class);
        } catch (Exception e) {
            logger.error("合同作废失败: " + e.getMessage(), e);
            e.printStackTrace();
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "合同作废失败: " + e.getMessage(), null);
        }
    }

    /**
     * 供水合同
     */
    private static final String[] WATER_CONTRACT = {ContractTypeEnum.CONTRACT_TYPE_0.getContractType(), ContractTypeEnum.CONTRACT_TYPE_1.getContractType(), ContractTypeEnum.CONTRACT_TYPE_2.getContractType(), ContractTypeEnum.CONTRACT_TYPE_3.getContractType()};

    /**
     * 校验合同字段
     *
     * @return
     */
    public void checkContractManageBean(ContractManageBean bean, UserInfoBean userInfo) {
        if (StringUtils.isBlank(bean.getProjectId())) {
            throw new ContractException("参数中的报装单ID不能为空！");
        }
        if (Arrays.asList(WATER_CONTRACT).contains(bean.getContractType()) && StringUtils.isBlank(bean.getUserNo())) {
            throw new ContractException("参数中的户号不能为空！");
        }
        if (StringUtils.isBlank(bean.getRecordId())&&StringUtils.equalsAny(bean.getContractType(),ContractTypeEnum.CONTRACT_TYPE_0.getContractType(),
                ContractTypeEnum.CONTRACT_TYPE_2.getContractType(),ContractTypeEnum.CONTRACT_TYPE_4.getContractType()
                )) {

            throw new ContractException("参数中的电子合同ID不能为空！");
        }
        if (StringUtils.isBlank(bean.getContractNo())) {
            throw new ContractException("参数中的合同编码不能为空！");
        }
        if (StringUtils.isBlank(bean.getContractType())) {
            throw new ContractException("参数中的合同类型不能为空！");
        }
        if (StringUtils.isBlank(bean.getContractStatus())) {
            throw new ContractException("参数中的合同状态不能为空！");
        }
        if (ContractStatusEnum.CONTRACT_STATUS_6.getContractStatus().equals(bean.getContractStatus())) {
            throw new ContractException("参数中的合同已作废，无需重复作废！");
        }

        if (!ALLOW_CANCEL_CONTRACT_STATUS.contains(bean.getContractStatus())) {
            //如果合同状态为1,2,7，则可作废
            throw new ContractException("只有进行中、签约完成、已上传合同附件状态的合同才能作废！");
        }
    }

    /**
     * 更新合同表中作废状态
     *
     * @param bean
     * @param userInfo
     * @param mapper
     * @return
     */
    public int deleteContract(ContractManageBean bean, UserInfoBean userInfo, ContractManageMapper mapper) {
        ContractManageBean updateContractBean = new ContractManageBean();
        updateContractBean.setUserNo(bean.getUserNo());
        updateContractBean.setContractNo(bean.getContractNo());
        // 合同撤回
        if (ContractStatusEnum.CONTRACT_STATUS_1.getContractStatus().equals(bean.getContractStatus())) {
            updateContractBean.setComments("合同撤回");
        } else {
            updateContractBean.setComments("合同作废");
        }
        updateContractBean.setContractStatus(ContractStatusEnum.CONTRACT_STATUS_6.getContractStatus());
        updateContractBean.setUpdateInfo(userInfo);
        int result = mapper.updateContract(updateContractBean);
        return result;
    }
}
